package com.ywz.framework.mybatisplus;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.ywz.common.SymmetricAlgorithmUtils;
import com.ywz.framework.property.MysqlProperties;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * 类描述-> MyBatisPlus配置
 *
 * @Author: ywz
 * @Date: 2024/09/29
 */
@Configuration
@AllArgsConstructor
public class MybatisPlusConfig {

    private final MysqlProperties mysqlProperties;

    /**
     * MyBatisPlus拦截器
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public DataSource getDataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(SymmetricAlgorithmUtils.decrypt(mysqlProperties.url()) + mysqlProperties.urlSuffix());
        hikariConfig.setUsername(SymmetricAlgorithmUtils.decrypt(mysqlProperties.username()));
        hikariConfig.setPassword(SymmetricAlgorithmUtils.decrypt(mysqlProperties.password()));
        hikariConfig.setDriverClassName(mysqlProperties.driverClassName());
        return new HikariDataSource(hikariConfig);
    }
}
